/**
 * 
 */
package com.hp.bon.sgw.threads;

import java.util.List;

import org.slf4j.LoggerFactory;

import com.hp.bon.security.bean.BonKeySendMessage;
import com.hp.bon.security.config.BonPublicKey;
import com.hp.bon.security.config.ConfigChgFreqThread;
import com.hp.bon.security.config.OutDESKey;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.processor.BonConfSyncProcessor;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_UTF8String;

/**
 * 安全框架 消息发送线程
 * 
 * @author sunhaiy
 */
public class SecurityConfigThread extends ConfigChgFreqThread {

	final public static org.slf4j.Logger logger = LoggerFactory.getLogger(SecurityConfigThread.class);

	private static SecurityConfigThread _instance;

	public static SecurityConfigThread getInstance() {
		if (_instance == null) {
			_instance = new SecurityConfigThread();
		}
		return _instance;
	}

	@Override
	public void sendRequestBONKeyConfig(List<BonKeySendMessage> keyMessage) {
		AVP srvCtxAVP = null;
		String serviceCtxID = null;
		AVP sessionIDAVP = null;
		for (BonKeySendMessage des : keyMessage) {
			srvCtxAVP = des.getMsg().find(Constants.DIAMETER_AVP_SERVICE_CONTEXT_ID);
			sessionIDAVP = des.getMsg().find(Constants.DIAMETER_AVP_SESSION_ID);
			String sessionID = new AVP_UTF8String(sessionIDAVP).queryValue();
			serviceCtxID = new AVP_UTF8String(srvCtxAVP).queryValue();
			// des.getMsg().setStateObject(des.getKey());
					
			BonConfSyncProcessor process = new BonConfSyncProcessor();
			CallParam newCallParam = new CallParam(sessionID, serviceCtxID, des.getMsg(), null, null);
			newCallParam.setProcessor(process);
			int result = BuzProcessorManager.sendCallParam(newCallParam);
			// logger.info(des.getMsg().getDictionary().toString());
			if (des.getKey() instanceof BonPublicKey) {
				logger.info("prepare send public key,version:" + des.getKey().getKeyVersion() + ",sessionId:" + sessionID);
			} else if (des.getKey() instanceof OutDESKey) {
				logger.info("prepare send des key,version:" + des.getKey().getNeCategoryAndDomain() + "|" + des.getKey().getKeyVersion() + " to " + des.getKey().getNeCategoryAndDomain() + ",sessionId:" + sessionID);
			}
			if (result != Constants.ResultCode.SUCCESS) {
				logger.warn("send Security key failed:" + result);
			}

		}

	}

}
